package com.sino.man.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;

import com.sino.man.dao.bean.UserBean;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.afterturn.easypoi.handler.inter.IExcelDataHandler;

@RestController
@RequestMapping("/web")
public class ExcelImportController {

    private static final Logger log = LoggerFactory.getLogger(ExcelImportController.class);

    @PostMapping("input")
    public void excelImport(@RequestParam("file") MultipartFile file) {
        ImportParams importParams = new ImportParams();

        // 需要验证
        importParams.setNeedVerfiy(true);

        try {
            ExcelImportResult<UserBean> result = ExcelImportUtil.importExcelMore(file.getInputStream(), UserBean.class,
                    importParams);

            List<UserBean> successList = result.getList();
            List<UserBean> failList = result.getFailList();

            log.info("是否存在验证未通过的数据:" + result.isVerfiyFail());
            log.info("验证通过的数量:" + successList.size());
            log.info("验证未通过的数量:" + failList.size());

            for (UserBean user : successList) {
                log.info("成功列表信息:ID=" + user.getId() + user.getName() + "-"
                        + new SimpleDateFormat("yyyy-MM-dd").format(user.getBirthday()));
            }
            for (UserBean user : failList) {
                log.info("失败列表信息:" + user.getName());
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}